{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "source": [
        "!pip install primisai openai nest-asyncio\n",
        "\n",
        "import os\n",
        "import nest_asyncio\n",
        "from primisai.nexus.core import AI, Agent, Supervisor\n",
        "from primisai.nexus.utils.debugger import Debugger\n",
        "import json\n",
        "\n",
        "nest_asyncio.apply()"
      ],
      "metadata": {
        "collapsed": true,
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "GTxCSY_zViVJ",
        "outputId": "8f9a2128-30d2-4a68-bd46-fd838ed35942"
      },
      "execution_count": 15,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Requirement already satisfied: primisai in /usr/local/lib/python3.11/dist-packages (0.7.0)\n",
            "Requirement already satisfied: openai in /usr/local/lib/python3.11/dist-packages (1.66.3)\n",
            "Requirement already satisfied: nest-asyncio in /usr/local/lib/python3.11/dist-packages (1.6.0)\n",
            "Requirement already satisfied: python-dotenv==1.0.1 in /usr/local/lib/python3.11/dist-packages (from primisai) (1.0.1)\n",
            "Requirement already satisfied: streamlit>=1.38.0 in /usr/local/lib/python3.11/dist-packages (from primisai) (1.46.1)\n",
            "Requirement already satisfied: pytest==8.3.4 in /usr/local/lib/python3.11/dist-packages (from primisai) (8.3.4)\n",
            "Requirement already satisfied: PyYAML==6.0.2 in /usr/local/lib/python3.11/dist-packages (from primisai) (6.0.2)\n",
            "Requirement already satisfied: mcp==1.6.0 in /usr/local/lib/python3.11/dist-packages (from mcp[cli]==1.6.0->primisai) (1.6.0)\n",
            "Requirement already satisfied: anyio<5,>=3.5.0 in /usr/local/lib/python3.11/dist-packages (from openai) (4.9.0)\n",
            "Requirement already satisfied: distro<2,>=1.7.0 in /usr/local/lib/python3.11/dist-packages (from openai) (1.9.0)\n",
            "Requirement already satisfied: httpx<1,>=0.23.0 in /usr/local/lib/python3.11/dist-packages (from openai) (0.28.1)\n",
            "Requirement already satisfied: jiter<1,>=0.4.0 in /usr/local/lib/python3.11/dist-packages (from openai) (0.10.0)\n",
            "Requirement already satisfied: pydantic<3,>=1.9.0 in /usr/local/lib/python3.11/dist-packages (from openai) (2.11.7)\n",
            "Requirement already satisfied: sniffio in /usr/local/lib/python3.11/dist-packages (from openai) (1.3.1)\n",
            "Requirement already satisfied: tqdm>4 in /usr/local/lib/python3.11/dist-packages (from openai) (4.67.1)\n",
            "Requirement already satisfied: typing-extensions<5,>=4.11 in /usr/local/lib/python3.11/dist-packages (from openai) (4.14.0)\n",
            "Requirement already satisfied: httpx-sse>=0.4 in /usr/local/lib/python3.11/dist-packages (from mcp==1.6.0->mcp[cli]==1.6.0->primisai) (0.4.1)\n",
            "Requirement already satisfied: pydantic-settings>=2.5.2 in /usr/local/lib/python3.11/dist-packages (from mcp==1.6.0->mcp[cli]==1.6.0->primisai) (2.10.1)\n",
            "Requirement already satisfied: sse-starlette>=1.6.1 in /usr/local/lib/python3.11/dist-packages (from mcp==1.6.0->mcp[cli]==1.6.0->primisai) (2.3.6)\n",
            "Requirement already satisfied: starlette>=0.27 in /usr/local/lib/python3.11/dist-packages (from mcp==1.6.0->mcp[cli]==1.6.0->primisai) (0.46.2)\n",
            "Requirement already satisfied: uvicorn>=0.23.1 in /usr/local/lib/python3.11/dist-packages (from mcp==1.6.0->mcp[cli]==1.6.0->primisai) (0.34.3)\n",
            "Requirement already satisfied: typer>=0.12.4 in /usr/local/lib/python3.11/dist-packages (from mcp[cli]==1.6.0->primisai) (0.16.0)\n",
            "Requirement already satisfied: iniconfig in /usr/local/lib/python3.11/dist-packages (from pytest==8.3.4->primisai) (2.1.0)\n",
            "Requirement already satisfied: packaging in /usr/local/lib/python3.11/dist-packages (from pytest==8.3.4->primisai) (24.2)\n",
            "Requirement already satisfied: pluggy<2,>=1.5 in /usr/local/lib/python3.11/dist-packages (from pytest==8.3.4->primisai) (1.6.0)\n",
            "Requirement already satisfied: idna>=2.8 in /usr/local/lib/python3.11/dist-packages (from anyio<5,>=3.5.0->openai) (3.10)\n",
            "Requirement already satisfied: certifi in /usr/local/lib/python3.11/dist-packages (from httpx<1,>=0.23.0->openai) (2025.6.15)\n",
            "Requirement already satisfied: httpcore==1.* in /usr/local/lib/python3.11/dist-packages (from httpx<1,>=0.23.0->openai) (1.0.9)\n",
            "Requirement already satisfied: h11>=0.16 in /usr/local/lib/python3.11/dist-packages (from httpcore==1.*->httpx<1,>=0.23.0->openai) (0.16.0)\n",
            "Requirement already satisfied: annotated-types>=0.6.0 in /usr/local/lib/python3.11/dist-packages (from pydantic<3,>=1.9.0->openai) (0.7.0)\n",
            "Requirement already satisfied: pydantic-core==2.33.2 in /usr/local/lib/python3.11/dist-packages (from pydantic<3,>=1.9.0->openai) (2.33.2)\n",
            "Requirement already satisfied: typing-inspection>=0.4.0 in /usr/local/lib/python3.11/dist-packages (from pydantic<3,>=1.9.0->openai) (0.4.1)\n",
            "Requirement already satisfied: altair<6,>=4.0 in /usr/local/lib/python3.11/dist-packages (from streamlit>=1.38.0->primisai) (5.5.0)\n",
            "Requirement already satisfied: blinker<2,>=1.5.0 in /usr/local/lib/python3.11/dist-packages (from streamlit>=1.38.0->primisai) (1.9.0)\n",
            "Requirement already satisfied: cachetools<7,>=4.0 in /usr/local/lib/python3.11/dist-packages (from streamlit>=1.38.0->primisai) (5.5.2)\n",
            "Requirement already satisfied: click<9,>=7.0 in /usr/local/lib/python3.11/dist-packages (from streamlit>=1.38.0->primisai) (8.2.1)\n",
            "Requirement already satisfied: numpy<3,>=1.23 in /usr/local/lib/python3.11/dist-packages (from streamlit>=1.38.0->primisai) (2.0.2)\n",
            "Requirement already satisfied: pandas<3,>=1.4.0 in /usr/local/lib/python3.11/dist-packages (from streamlit>=1.38.0->primisai) (2.2.2)\n",
            "Requirement already satisfied: pillow<12,>=7.1.0 in /usr/local/lib/python3.11/dist-packages (from streamlit>=1.38.0->primisai) (11.2.1)\n",
            "Requirement already satisfied: protobuf<7,>=3.20 in /usr/local/lib/python3.11/dist-packages (from streamlit>=1.38.0->primisai) (5.29.5)\n",
            "Requirement already satisfied: pyarrow>=7.0 in /usr/local/lib/python3.11/dist-packages (from streamlit>=1.38.0->primisai) (18.1.0)\n",
            "Requirement already satisfied: requests<3,>=2.27 in /usr/local/lib/python3.11/dist-packages (from streamlit>=1.38.0->primisai) (2.32.3)\n",
            "Requirement already satisfied: tenacity<10,>=8.1.0 in /usr/local/lib/python3.11/dist-packages (from streamlit>=1.38.0->primisai) (8.5.0)\n",
            "Requirement already satisfied: toml<2,>=0.10.1 in /usr/local/lib/python3.11/dist-packages (from streamlit>=1.38.0->primisai) (0.10.2)\n",
            "Requirement already satisfied: watchdog<7,>=2.1.5 in /usr/local/lib/python3.11/dist-packages (from streamlit>=1.38.0->primisai) (6.0.0)\n",
            "Requirement already satisfied: gitpython!=3.1.19,<4,>=3.0.7 in /usr/local/lib/python3.11/dist-packages (from streamlit>=1.38.0->primisai) (3.1.44)\n",
            "Requirement already satisfied: pydeck<1,>=0.8.0b4 in /usr/local/lib/python3.11/dist-packages (from streamlit>=1.38.0->primisai) (0.9.1)\n",
            "Requirement already satisfied: tornado!=6.5.0,<7,>=6.0.3 in /usr/local/lib/python3.11/dist-packages (from streamlit>=1.38.0->primisai) (6.4.2)\n",
            "Requirement already satisfied: jinja2 in /usr/local/lib/python3.11/dist-packages (from altair<6,>=4.0->streamlit>=1.38.0->primisai) (3.1.6)\n",
            "Requirement already satisfied: jsonschema>=3.0 in /usr/local/lib/python3.11/dist-packages (from altair<6,>=4.0->streamlit>=1.38.0->primisai) (4.24.0)\n",
            "Requirement already satisfied: narwhals>=1.14.2 in /usr/local/lib/python3.11/dist-packages (from altair<6,>=4.0->streamlit>=1.38.0->primisai) (1.44.0)\n",
            "Requirement already satisfied: gitdb<5,>=4.0.1 in /usr/local/lib/python3.11/dist-packages (from gitpython!=3.1.19,<4,>=3.0.7->streamlit>=1.38.0->primisai) (4.0.12)\n",
            "Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.11/dist-packages (from pandas<3,>=1.4.0->streamlit>=1.38.0->primisai) (2.9.0.post0)\n",
            "Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.11/dist-packages (from pandas<3,>=1.4.0->streamlit>=1.38.0->primisai) (2025.2)\n",
            "Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.11/dist-packages (from pandas<3,>=1.4.0->streamlit>=1.38.0->primisai) (2025.2)\n",
            "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.11/dist-packages (from requests<3,>=2.27->streamlit>=1.38.0->primisai) (3.4.2)\n",
            "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.11/dist-packages (from requests<3,>=2.27->streamlit>=1.38.0->primisai) (2.4.0)\n",
            "Requirement already satisfied: shellingham>=1.3.0 in /usr/local/lib/python3.11/dist-packages (from typer>=0.12.4->mcp[cli]==1.6.0->primisai) (1.5.4)\n",
            "Requirement already satisfied: rich>=10.11.0 in /usr/local/lib/python3.11/dist-packages (from typer>=0.12.4->mcp[cli]==1.6.0->primisai) (13.9.4)\n",
            "Requirement already satisfied: smmap<6,>=3.0.1 in /usr/local/lib/python3.11/dist-packages (from gitdb<5,>=4.0.1->gitpython!=3.1.19,<4,>=3.0.7->streamlit>=1.38.0->primisai) (5.0.2)\n",
            "Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.11/dist-packages (from jinja2->altair<6,>=4.0->streamlit>=1.38.0->primisai) (3.0.2)\n",
            "Requirement already satisfied: attrs>=22.2.0 in /usr/local/lib/python3.11/dist-packages (from jsonschema>=3.0->altair<6,>=4.0->streamlit>=1.38.0->primisai) (25.3.0)\n",
            "Requirement already satisfied: jsonschema-specifications>=2023.03.6 in /usr/local/lib/python3.11/dist-packages (from jsonschema>=3.0->altair<6,>=4.0->streamlit>=1.38.0->primisai) (2025.4.1)\n",
            "Requirement already satisfied: referencing>=0.28.4 in /usr/local/lib/python3.11/dist-packages (from jsonschema>=3.0->altair<6,>=4.0->streamlit>=1.38.0->primisai) (0.36.2)\n",
            "Requirement already satisfied: rpds-py>=0.7.1 in /usr/local/lib/python3.11/dist-packages (from jsonschema>=3.0->altair<6,>=4.0->streamlit>=1.38.0->primisai) (0.25.1)\n",
            "Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.11/dist-packages (from python-dateutil>=2.8.2->pandas<3,>=1.4.0->streamlit>=1.38.0->primisai) (1.17.0)\n",
            "Requirement already satisfied: markdown-it-py>=2.2.0 in /usr/local/lib/python3.11/dist-packages (from rich>=10.11.0->typer>=0.12.4->mcp[cli]==1.6.0->primisai) (3.0.0)\n",
            "Requirement already satisfied: pygments<3.0.0,>=2.13.0 in /usr/local/lib/python3.11/dist-packages (from rich>=10.11.0->typer>=0.12.4->mcp[cli]==1.6.0->primisai) (2.19.2)\n",
            "Requirement already satisfied: mdurl~=0.1 in /usr/local/lib/python3.11/dist-packages (from markdown-it-py>=2.2.0->rich>=10.11.0->typer>=0.12.4->mcp[cli]==1.6.0->primisai) (0.1.2)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(\"🚀 PrimisAI Nexus Advanced Tutorial with OpenAI API\")\n",
        "print(\"=\" * 55)\n",
        "\n",
        "os.environ[\"OPENAI_API_KEY\"] = \"Use Your Own API Key Here5\"\n",
        "\n",
        "# llm_config = {\n",
        "#     \"api_key\": os.environ[\"OPENAI_API_KEY\"],\n",
        "#     \"model\": \"gpt-4o-mini\",\n",
        "#     \"base_url\": \"https://api.openai.com/v1\",\n",
        "#     \"temperature\": 0.7\n",
        "# }\n",
        "\n",
        "\n",
        "llm_config = {\n",
        "    \"api_key\": os.environ[\"OPENAI_API_KEY\"],\n",
        "    \"model\": \"gpt-3.5-turbo\",\n",
        "    \"base_url\": \"https://api.openai.com/v1\",\n",
        "    \"temperature\": 0.7\n",
        "}\n",
        "\n",
        "\n",
        "print(\"📋 API Configuration:\")\n",
        "print(f\"• Model: {llm_config['model']}\")\n",
        "print(f\"• Base URL: {llm_config['base_url']}\")\n",
        "print(\"• Note: OpenAI has limited free tokens through April 2025\")\n",
        "print(\"• Alternative: Consider Puter.js for unlimited free access\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "_X4lX5OPVjlr",
        "outputId": "95224979-5fe8-4da6-8caf-b02afa311b94"
      },
      "execution_count": 16,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "🚀 PrimisAI Nexus Advanced Tutorial with OpenAI API\n",
            "=======================================================\n",
            "📋 API Configuration:\n",
            "• Model: gpt-3.5-turbo\n",
            "• Base URL: https://api.openai.com/v1\n",
            "• Note: OpenAI has limited free tokens through April 2025\n",
            "• Alternative: Consider Puter.js for unlimited free access\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "code_schema = {\n",
        "    \"type\": \"object\",\n",
        "    \"properties\": {\n",
        "        \"description\": {\"type\": \"string\", \"description\": \"Code explanation\"},\n",
        "        \"code\": {\"type\": \"string\", \"description\": \"Python code implementation\"},\n",
        "        \"language\": {\"type\": \"string\", \"description\": \"Programming language\"},\n",
        "        \"complexity\": {\"type\": \"string\", \"enum\": [\"beginner\", \"intermediate\", \"advanced\"]},\n",
        "        \"test_cases\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}, \"description\": \"Example usage\"}\n",
        "    },\n",
        "    \"required\": [\"description\", \"code\", \"language\"]\n",
        "}\n",
        "\n",
        "analysis_schema = {\n",
        "    \"type\": \"object\",\n",
        "    \"properties\": {\n",
        "        \"summary\": {\"type\": \"string\", \"description\": \"Brief analysis summary\"},\n",
        "        \"insights\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}, \"description\": \"Key insights\"},\n",
        "        \"recommendations\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}, \"description\": \"Action items\"},\n",
        "        \"confidence\": {\"type\": \"number\", \"minimum\": 0, \"maximum\": 1},\n",
        "        \"methodology\": {\"type\": \"string\", \"description\": \"Analysis approach used\"}\n",
        "    },\n",
        "    \"required\": [\"summary\", \"insights\", \"confidence\"]\n",
        "}\n",
        "\n",
        "planning_schema = {\n",
        "    \"type\": \"object\",\n",
        "    \"properties\": {\n",
        "        \"tasks\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}, \"description\": \"List of tasks to complete\"},\n",
        "        \"priority\": {\"type\": \"string\", \"enum\": [\"low\", \"medium\", \"high\"]},\n",
        "        \"estimated_time\": {\"type\": \"string\", \"description\": \"Time estimate\"},\n",
        "        \"dependencies\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}, \"description\": \"Task dependencies\"}\n",
        "    },\n",
        "    \"required\": [\"tasks\", \"priority\"]\n",
        "}"
      ],
      "metadata": {
        "id": "ALrW1HF9V1Ub"
      },
      "execution_count": 17,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "def calculate_metrics(data_str):\n",
        "    \"\"\"Calculate comprehensive statistics for numerical data\"\"\"\n",
        "    try:\n",
        "        data = json.loads(data_str) if isinstance(data_str, str) else data_str\n",
        "        if isinstance(data, list) and all(isinstance(x, (int, float)) for x in data):\n",
        "            import statistics\n",
        "            return {\n",
        "                \"mean\": statistics.mean(data),\n",
        "                \"median\": statistics.median(data),\n",
        "                \"mode\": statistics.mode(data) if len(set(data)) < len(data) else \"No mode\",\n",
        "                \"std_dev\": statistics.stdev(data) if len(data) > 1 else 0,\n",
        "                \"max\": max(data),\n",
        "                \"min\": min(data),\n",
        "                \"count\": len(data),\n",
        "                \"sum\": sum(data)\n",
        "            }\n",
        "        return {\"error\": \"Invalid data format - expecting array of numbers\"}\n",
        "    except Exception as e:\n",
        "        return {\"error\": f\"Could not parse data: {str(e)}\"}\n",
        "\n",
        "def validate_code(code):\n",
        "    \"\"\"Advanced code validation with syntax and basic security checks\"\"\"\n",
        "    try:\n",
        "        dangerous_imports = ['os', 'subprocess', 'eval', 'exec', '__import__']\n",
        "        security_warnings = []\n",
        "\n",
        "        for danger in dangerous_imports:\n",
        "            if danger in code:\n",
        "                security_warnings.append(f\"Potentially dangerous: {danger}\")\n",
        "\n",
        "        compile(code, '<string>', 'exec')\n",
        "\n",
        "        return {\n",
        "            \"valid\": True,\n",
        "            \"message\": \"Code syntax is valid\",\n",
        "            \"security_warnings\": security_warnings,\n",
        "            \"lines\": len(code.split('\\n'))\n",
        "        }\n",
        "    except SyntaxError as e:\n",
        "        return {\n",
        "            \"valid\": False,\n",
        "            \"message\": f\"Syntax error: {e}\",\n",
        "            \"line\": getattr(e, 'lineno', 'unknown'),\n",
        "            \"security_warnings\": []\n",
        "        }\n",
        "\n",
        "def search_documentation(query):\n",
        "    \"\"\"Simulate searching documentation (placeholder function)\"\"\"\n",
        "    docs = {\n",
        "        \"python\": \"Python is a high-level programming language\",\n",
        "        \"list\": \"Lists are ordered, mutable collections in Python\",\n",
        "        \"function\": \"Functions are reusable blocks of code\",\n",
        "        \"class\": \"Classes define objects with attributes and methods\"\n",
        "    }\n",
        "\n",
        "    results = []\n",
        "    for key, value in docs.items():\n",
        "        if query.lower() in key.lower():\n",
        "            results.append(f\"{key}: {value}\")\n",
        "\n",
        "    return {\n",
        "        \"query\": query,\n",
        "        \"results\": results if results else [\"No documentation found\"],\n",
        "        \"total_results\": len(results)\n",
        "    }"
      ],
      "metadata": {
        "id": "Yhxcgs6bV7NW"
      },
      "execution_count": 18,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "print(\"\\n📋 Setting up Multi-Agent Hierarchy with OpenAI\")\n",
        "\n",
        "main_supervisor = Supervisor(\n",
        "    name=\"ProjectManager\",\n",
        "    llm_config=llm_config,\n",
        "    system_message=\"You are a senior project manager coordinating development and analysis tasks. Delegate appropriately, provide clear summaries, and ensure quality delivery. Always consider time estimates and dependencies.\"\n",
        ")\n",
        "\n",
        "dev_supervisor = Supervisor(\n",
        "    name=\"DevManager\",\n",
        "    llm_config=llm_config,\n",
        "    is_assistant=True,\n",
        "    system_message=\"You manage development tasks. Coordinate between coding, testing, and code review. Ensure best practices and security.\"\n",
        ")\n",
        "\n",
        "analysis_supervisor = Supervisor(\n",
        "    name=\"AnalysisManager\",\n",
        "    llm_config=llm_config,\n",
        "    is_assistant=True,\n",
        "    system_message=\"You manage data analysis and research tasks. Ensure thorough analysis, statistical rigor, and actionable insights.\"\n",
        ")\n",
        "\n",
        "qa_supervisor = Supervisor(\n",
        "    name=\"QAManager\",\n",
        "    llm_config=llm_config,\n",
        "    is_assistant=True,\n",
        "    system_message=\"You manage quality assurance and testing. Ensure thorough validation and documentation.\"\n",
        ")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "g1DwDdLBV_J9",
        "outputId": "32b7c0c3-469c-43b8-b4b1-798f7931ac31"
      },
      "execution_count": 19,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "📋 Setting up Multi-Agent Hierarchy with OpenAI\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "code_agent = Agent(\n",
        "    name=\"CodeWriter\",\n",
        "    llm_config=llm_config,\n",
        "    system_message=\"You are an expert Python developer. Write clean, efficient, well-documented code with proper error handling. Always include test cases and follow PEP 8 standards.\",\n",
        "    output_schema=code_schema,\n",
        "    tools=[{\n",
        "        \"metadata\": {\n",
        "            \"function\": {\n",
        "                \"name\": \"validate_code\",\n",
        "                \"description\": \"Validates Python code syntax and checks for security issues\",\n",
        "                \"parameters\": {\n",
        "                    \"type\": \"object\",\n",
        "                    \"properties\": {\n",
        "                        \"code\": {\"type\": \"string\", \"description\": \"Python code to validate\"}\n",
        "                    },\n",
        "                    \"required\": [\"code\"]\n",
        "                }\n",
        "            }\n",
        "        },\n",
        "        \"tool\": validate_code\n",
        "    }, {\n",
        "        \"metadata\": {\n",
        "            \"function\": {\n",
        "                \"name\": \"search_documentation\",\n",
        "                \"description\": \"Search for programming documentation and examples\",\n",
        "                \"parameters\": {\n",
        "                    \"type\": \"object\",\n",
        "                    \"properties\": {\n",
        "                        \"query\": {\"type\": \"string\", \"description\": \"Documentation topic to search for\"}\n",
        "                    },\n",
        "                    \"required\": [\"query\"]\n",
        "                }\n",
        "            }\n",
        "        },\n",
        "        \"tool\": search_documentation\n",
        "    }],\n",
        "    use_tools=True\n",
        ")\n",
        "\n",
        "review_agent = Agent(\n",
        "    name=\"CodeReviewer\",\n",
        "    llm_config=llm_config,\n",
        "    system_message=\"You are a senior code reviewer. Analyze code for best practices, efficiency, security, maintainability, and potential issues. Provide constructive feedback and suggestions.\",\n",
        "    keep_history=True,\n",
        "    tools=[{\n",
        "        \"metadata\": {\n",
        "            \"function\": {\n",
        "                \"name\": \"validate_code\",\n",
        "                \"description\": \"Validates code syntax and security\",\n",
        "                \"parameters\": {\n",
        "                    \"type\": \"object\",\n",
        "                    \"properties\": {\n",
        "                        \"code\": {\"type\": \"string\", \"description\": \"Code to validate\"}\n",
        "                    },\n",
        "                    \"required\": [\"code\"]\n",
        "                }\n",
        "            }\n",
        "        },\n",
        "        \"tool\": validate_code\n",
        "    }],\n",
        "    use_tools=True\n",
        ")\n",
        "\n",
        "analyst_agent = Agent(\n",
        "    name=\"DataAnalyst\",\n",
        "    llm_config=llm_config,\n",
        "    system_message=\"You are a data scientist specializing in statistical analysis and insights generation. Provide thorough analysis with confidence metrics and actionable recommendations.\",\n",
        "    output_schema=analysis_schema,\n",
        "    tools=[{\n",
        "        \"metadata\": {\n",
        "            \"function\": {\n",
        "                \"name\": \"calculate_metrics\",\n",
        "                \"description\": \"Calculates comprehensive statistics for numerical data\",\n",
        "                \"parameters\": {\n",
        "                    \"type\": \"object\",\n",
        "                    \"properties\": {\n",
        "                        \"data_str\": {\"type\": \"string\", \"description\": \"JSON string of numerical data array\"}\n",
        "                    },\n",
        "                    \"required\": [\"data_str\"]\n",
        "                }\n",
        "            }\n",
        "        },\n",
        "        \"tool\": calculate_metrics\n",
        "    }],\n",
        "    use_tools=True\n",
        ")\n",
        "\n",
        "planner_agent = Agent(\n",
        "    name=\"ProjectPlanner\",\n",
        "    llm_config=llm_config,\n",
        "    system_message=\"You are a project planning specialist. Break down complex projects into manageable tasks with realistic time estimates and clear dependencies.\",\n",
        "    output_schema=planning_schema\n",
        ")\n",
        "\n",
        "tester_agent = Agent(\n",
        "    name=\"QATester\",\n",
        "    llm_config=llm_config,\n",
        "    system_message=\"You are a QA specialist focused on comprehensive testing strategies, edge cases, and quality assurance.\",\n",
        "    tools=[{\n",
        "        \"metadata\": {\n",
        "            \"function\": {\n",
        "                \"name\": \"validate_code\",\n",
        "                \"description\": \"Validates code for testing\",\n",
        "                \"parameters\": {\n",
        "                    \"type\": \"object\",\n",
        "                    \"properties\": {\n",
        "                        \"code\": {\"type\": \"string\", \"description\": \"Code to test\"}\n",
        "                    },\n",
        "                    \"required\": [\"code\"]\n",
        "                }\n",
        "            }\n",
        "        },\n",
        "        \"tool\": validate_code\n",
        "    }],\n",
        "    use_tools=True\n",
        ")"
      ],
      "metadata": {
        "id": "mmV0yIqPWDCq"
      },
      "execution_count": 20,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "dev_supervisor.register_agent(code_agent)\n",
        "dev_supervisor.register_agent(review_agent)\n",
        "analysis_supervisor.register_agent(analyst_agent)\n",
        "qa_supervisor.register_agent(tester_agent)\n",
        "\n",
        "main_supervisor.register_agent(dev_supervisor)\n",
        "main_supervisor.register_agent(analysis_supervisor)\n",
        "main_supervisor.register_agent(qa_supervisor)\n",
        "main_supervisor.register_agent(planner_agent)"
      ],
      "metadata": {
        "id": "B-LxRVddWIzq"
      },
      "execution_count": 21,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "print(\"\\n🌳 Agent Hierarchy:\")\n",
        "main_supervisor.display_agent_graph()\n",
        "\n",
        "print(\"\\n🧪 Testing Full Multi-Agent Communication\")\n",
        "print(\"-\" * 45)\n",
        "\n",
        "try:\n",
        "    test_response = main_supervisor.chat(\"Hello! Please introduce your team and explain how you coordinate complex projects.\")\n",
        "    print(f\"✅ Supervisor communication test successful!\")\n",
        "    print(f\"Response preview: {test_response[:200]}...\")\n",
        "except Exception as e:\n",
        "    print(f\"❌ Supervisor test failed: {str(e)}\")\n",
        "    print(\"Falling back to direct agent testing...\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "nQCsUgOEWP6o",
        "outputId": "b3590ee6-a384-48ff-e82a-69ef26d88611"
      },
      "execution_count": 22,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "🌳 Agent Hierarchy:\n",
            "Main Supervisor: ProjectManager\n",
            "│\n",
            "├── Assistant Supervisor: DevManager\n",
            "│   ├── Agent: CodeWriter\n",
            "│   │   ├── Tool: validate_code\n",
            "│   │   └── Tool: search_documentation\n",
            "│   │\n",
            "│   └── Agent: CodeReviewer\n",
            "│       └── Tool: validate_code\n",
            "│\n",
            "├── Assistant Supervisor: AnalysisManager\n",
            "│   └── Agent: DataAnalyst\n",
            "│       └── Tool: calculate_metrics\n",
            "│\n",
            "├── Assistant Supervisor: QAManager\n",
            "│   └── Agent: QATester\n",
            "│       └── Tool: validate_code\n",
            "│\n",
            "└── Agent: ProjectPlanner\n",
            "    └── No tools available\n",
            "\n",
            "🧪 Testing Full Multi-Agent Communication\n",
            "---------------------------------------------\n",
            "❌ Supervisor test failed: Error in processing user input: Chat completion failed: Error code: 429 - {'error': {'message': 'You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.', 'type': 'insufficient_quota', 'param': None, 'code': 'insufficient_quota'}}\n",
            "Falling back to direct agent testing...\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(\"\\n🎯 Complex Multi-Agent Task Execution\")\n",
        "print(\"-\" * 40)\n",
        "\n",
        "complex_task = \"\"\"Create a Python function that implements a binary search algorithm,\n",
        "have it reviewed for optimization, tested thoroughly, and provide a project plan\n",
        "for integrating it into a larger search system.\"\"\"\n",
        "\n",
        "print(f\"Complex Task: {complex_task}\")\n",
        "\n",
        "try:\n",
        "    complex_response = main_supervisor.chat(complex_task)\n",
        "    print(f\"✅ Complex task completed\")\n",
        "    print(f\"Response: {complex_response[:300]}...\")\n",
        "except Exception as e:\n",
        "    print(f\"❌ Complex task failed: {str(e)}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "31ECa821WUbD",
        "outputId": "244c31b2-651e-4558-ef8d-fa8b8b7ff657"
      },
      "execution_count": 23,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "🎯 Complex Multi-Agent Task Execution\n",
            "----------------------------------------\n",
            "Complex Task: Create a Python function that implements a binary search algorithm, \n",
            "have it reviewed for optimization, tested thoroughly, and provide a project plan \n",
            "for integrating it into a larger search system.\n",
            "❌ Complex task failed: Error in processing user input: Chat completion failed: Error code: 429 - {'error': {'message': 'You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.', 'type': 'insufficient_quota', 'param': None, 'code': 'insufficient_quota'}}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(\"\\n🔧 Tool Integration & Structured Outputs\")\n",
        "print(\"-\" * 43)\n",
        "\n",
        "print(\"Testing Code Agent with tools...\")\n",
        "try:\n",
        "    code_response = code_agent.chat(\"Create a function to calculate fibonacci numbers with memoization\")\n",
        "    print(f\"✅ Code Agent with tools: Working\")\n",
        "    print(f\"Response type: {type(code_response)}\")\n",
        "\n",
        "    if isinstance(code_response, str) and code_response.strip().startswith('{'):\n",
        "        code_data = json.loads(code_response)\n",
        "        print(f\"  - Description: {code_data.get('description', 'N/A')[:50]}...\")\n",
        "        print(f\"  - Language: {code_data.get('language', 'N/A')}\")\n",
        "        print(f\"  - Complexity: {code_data.get('complexity', 'N/A')}\")\n",
        "    else:\n",
        "        print(f\"  - Raw response: {code_response[:100]}...\")\n",
        "\n",
        "except Exception as e:\n",
        "    print(f\"❌ Code Agent error: {str(e)}\")\n",
        "\n",
        "print(\"\\nTesting Analyst Agent with tools...\")\n",
        "try:\n",
        "    analysis_response = analyst_agent.chat(\"Analyze this sales data: [100, 150, 120, 180, 200, 175, 160, 190, 220, 185]. What trends do you see?\")\n",
        "    print(f\"✅ Analyst Agent with tools: Working\")\n",
        "\n",
        "    if isinstance(analysis_response, str) and analysis_response.strip().startswith('{'):\n",
        "        analysis_data = json.loads(analysis_response)\n",
        "        print(f\"  - Summary: {analysis_data.get('summary', 'N/A')[:50]}...\")\n",
        "        print(f\"  - Confidence: {analysis_data.get('confidence', 'N/A')}\")\n",
        "        print(f\"  - Insights count: {len(analysis_data.get('insights', []))}\")\n",
        "    else:\n",
        "        print(f\"  - Raw response: {analysis_response[:100]}...\")\n",
        "\n",
        "except Exception as e:\n",
        "    print(f\"❌ Analyst Agent error: {str(e)}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "hh7mcdcNWaw3",
        "outputId": "d1acc618-a5a3-4db4-a0d3-a5eda9fafa4f"
      },
      "execution_count": 24,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "🔧 Tool Integration & Structured Outputs\n",
            "-------------------------------------------\n",
            "Testing Code Agent with tools...\n",
            "❌ Code Agent error: Error in chat processing: Chat completion failed: Error code: 429 - {'error': {'message': 'You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.', 'type': 'insufficient_quota', 'param': None, 'code': 'insufficient_quota'}}\n",
            "\n",
            "Testing Analyst Agent with tools...\n",
            "❌ Analyst Agent error: Error in chat processing: Chat completion failed: Error code: 429 - {'error': {'message': 'You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.', 'type': 'insufficient_quota', 'param': None, 'code': 'insufficient_quota'}}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(\"\\n🔨 Manual Tool Usage\")\n",
        "print(\"-\" * 22)\n",
        "\n",
        "# Test all tools manually\n",
        "sample_data = \"[95, 87, 92, 88, 91, 89, 94, 90, 86, 93]\"\n",
        "metrics_result = calculate_metrics(sample_data)\n",
        "print(f\"Statistics for {sample_data}:\")\n",
        "for key, value in metrics_result.items():\n",
        "    print(f\"  {key}: {value}\")\n",
        "\n",
        "print(\"\\nCode validation test:\")\n",
        "test_code = \"\"\"\n",
        "def binary_search(arr, target):\n",
        "    left, right = 0, len(arr) - 1\n",
        "    while left <= right:\n",
        "        mid = (left + right) // 2\n",
        "        if arr[mid] == target:\n",
        "            return mid\n",
        "        elif arr[mid] < target:\n",
        "            left = mid + 1\n",
        "        else:\n",
        "            right = mid - 1\n",
        "    return -1\n",
        "\"\"\"\n",
        "validation_result = validate_code(test_code)\n",
        "print(f\"Validation result: {validation_result}\")\n",
        "\n",
        "print(\"\\nDocumentation search test:\")\n",
        "doc_result = search_documentation(\"python function\")\n",
        "print(f\"Search results: {doc_result}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "xD0J4We1Wek6",
        "outputId": "354d83a4-b028-450d-c019-ee5f1b8a19cc"
      },
      "execution_count": 25,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "🔨 Manual Tool Usage\n",
            "----------------------\n",
            "Statistics for [95, 87, 92, 88, 91, 89, 94, 90, 86, 93]:\n",
            "  mean: 90.5\n",
            "  median: 90.5\n",
            "  mode: No mode\n",
            "  std_dev: 3.0276503540974917\n",
            "  max: 95\n",
            "  min: 86\n",
            "  count: 10\n",
            "  sum: 905\n",
            "\n",
            "Code validation test:\n",
            "Validation result: {'valid': True, 'message': 'Code syntax is valid', 'security_warnings': [], 'lines': 13}\n",
            "\n",
            "Documentation search test:\n",
            "Search results: {'query': 'python function', 'results': ['No documentation found'], 'total_results': 0}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(\"\\n🚀 Advanced Multi-Agent Workflow\")\n",
        "print(\"-\" * 35)\n",
        "\n",
        "workflow_stages = [\n",
        "    (\"Planning\", \"Create a project plan for building a web scraper for news articles\"),\n",
        "    (\"Development\", \"Implement the web scraper with error handling and rate limiting\"),\n",
        "    (\"Review\", \"Review the web scraper code for security and efficiency\"),\n",
        "    (\"Testing\", \"Create comprehensive test cases for the web scraper\"),\n",
        "    (\"Analysis\", \"Analyze sample scraped data: [45, 67, 23, 89, 12, 56, 78, 34, 91, 43]\")\n",
        "]\n",
        "\n",
        "workflow_results = {}\n",
        "\n",
        "for stage, task in workflow_stages:\n",
        "    print(f\"\\n{stage} Stage: {task}\")\n",
        "    try:\n",
        "        if stage == \"Planning\":\n",
        "            response = planner_agent.chat(task)\n",
        "        elif stage == \"Development\":\n",
        "            response = code_agent.chat(task)\n",
        "        elif stage == \"Review\":\n",
        "            response = review_agent.chat(task)\n",
        "        elif stage == \"Testing\":\n",
        "            response = tester_agent.chat(task)\n",
        "        elif stage == \"Analysis\":\n",
        "            response = analyst_agent.chat(task)\n",
        "\n",
        "        workflow_results[stage] = response\n",
        "        print(f\"✅ {stage} completed: {response[:80]}...\")\n",
        "\n",
        "    except Exception as e:\n",
        "        print(f\"❌ {stage} failed: {str(e)}\")\n",
        "        workflow_results[stage] = f\"Error: {str(e)}\""
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "OI5BQL3SWkoG",
        "outputId": "00c26f1a-3236-462b-91f9-2971dd34216c"
      },
      "execution_count": 26,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "🚀 Advanced Multi-Agent Workflow\n",
            "-----------------------------------\n",
            "\n",
            "Planning Stage: Create a project plan for building a web scraper for news articles\n",
            "❌ Planning failed: Error in chat processing: Chat completion failed: Error code: 429 - {'error': {'message': 'You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.', 'type': 'insufficient_quota', 'param': None, 'code': 'insufficient_quota'}}\n",
            "\n",
            "Development Stage: Implement the web scraper with error handling and rate limiting\n",
            "❌ Development failed: Error in chat processing: Chat completion failed: Error code: 429 - {'error': {'message': 'You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.', 'type': 'insufficient_quota', 'param': None, 'code': 'insufficient_quota'}}\n",
            "\n",
            "Review Stage: Review the web scraper code for security and efficiency\n",
            "❌ Review failed: Error in chat processing: Chat completion failed: Error code: 429 - {'error': {'message': 'You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.', 'type': 'insufficient_quota', 'param': None, 'code': 'insufficient_quota'}}\n",
            "\n",
            "Testing Stage: Create comprehensive test cases for the web scraper\n",
            "❌ Testing failed: Error in chat processing: Chat completion failed: Error code: 429 - {'error': {'message': 'You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.', 'type': 'insufficient_quota', 'param': None, 'code': 'insufficient_quota'}}\n",
            "\n",
            "Analysis Stage: Analyze sample scraped data: [45, 67, 23, 89, 12, 56, 78, 34, 91, 43]\n",
            "❌ Analysis failed: Error in chat processing: Chat completion failed: Error code: 429 - {'error': {'message': 'You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.', 'type': 'insufficient_quota', 'param': None, 'code': 'insufficient_quota'}}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(\"\\n📊 System Monitoring & Performance\")\n",
        "print(\"-\" * 37)\n",
        "\n",
        "debugger = Debugger(name=\"OpenAITutorialDebugger\")\n",
        "debugger.log(\"Advanced OpenAI tutorial execution completed successfully\")\n",
        "\n",
        "print(f\"Main Supervisor ID: {main_supervisor.workflow_id}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "BT4RhHYKWpCw",
        "outputId": "c3a29e53-7708-4182-fb6f-5239a023ece8"
      },
      "execution_count": 27,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "📊 System Monitoring & Performance\n",
            "-------------------------------------\n",
            "Main Supervisor ID: 0d0b2bc3-b77e-4381-a647-f372f5709dee\n"
          ]
        }
      ]
    }
  ]
}